package com.lmx.common.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * Created by qin on 2016-6-17.
 * 读取properties文件
 */
public class PropertiesFileUtil {
    private static Log log = LogFactory.getLog(new PropertiesFileUtil().getClass());
    private static Properties applicationProperties;


    /**
     * 根据键获得相应的值
     * @param path 路径
     * @param key 键
     * @return
     */
    public static String getValueByKey(String path, String key) {
        Properties properties = getProperties(path);
        return  properties.getProperty(key);
    }

    /**
     * 获取配置文件
     * @param path
     * @return
     */
    public static Properties getProperties(String path){
        try {
        /*    //获取绝对路径
            String filePath = PropertiesFileUtil.class.getResource("/" + path).toString();
            //截掉路径的”file:“前缀
            filePath = filePath.substring(5);
            filePath = filePath.replace("%20", " ") ;
             InputStream in = new BufferedInputStream(new FileInputStream(filePath));*/
            log.debug("获取配置文件:"+ PropertiesFileUtil.class.getResource("/" + path));
            InputStream in = PropertiesFileUtil.class.getResourceAsStream("/" + path);
            Properties props = new Properties();
            props.load(in);
            in.close();
            log.debug(props.stringPropertyNames());
            return props ;
        } catch (IOException e) {
            log.error(e.toString());
            return null;
        }
    }

    public static Properties getApplicationProperties() {
        if(applicationProperties == null){
            applicationProperties = getProperties("application.properties");
        }
        return applicationProperties;
    }



    /*    public static void main(String[] args) {
//        System.out.println(getValueByKey("url.properties", "url"));
    }*/
}
